package com.acme.bankapp.account;


/**
 * @author Andrey Alekov
 * Checking account with overdraft.
 */
public class CheckingAccount extends AbstractAccount {
	private SavingAccount overdraft;
	private double overdraftLimit;
	
	/*
	 * 	@param amount the initial value.
	 */
	public CheckingAccount(double amount) {
		super(amount);
	}

	/*
	 * 	@param amount the initial value.
	 *  @param overdraft the initial overdraft value.
	 */
	public CheckingAccount(double amount, double overdraft) {
		super(amount);
		this.overdraft = new SavingAccount(overdraft);
		this.overdraftLimit = overdraft;
	}
	
	/*
	 * 	Get overdraft value.
	 *  @return overdraft value
	 */
	public double getOverdraft() {
		return this.overdraft.getBalance();
	}

	/*
	 * 	Set overdraft value.
	 *  @return overdraft value
	 */
	public void setOverdraft(double overdraft) {
		this.overdraft.setBalance(overdraft);;
	}

	/* (non-Javadoc)
	 * @see com.acme.bankapp.service.bank.AbstractAccount#maximumAmounToWithdraw()
	 * Return allowed balance with overdraft.
	 */
	@Override
	public double maximumAmountToWithdraw() {
		return (this.balance + this.overdraft.getBalance());
	}

	/*
	 * 	Deposit actual account with overdraft.
	 */
	@Override
	public void deposit(double amount) {
		this.balance += amount;
		double delta = this.overdraft.getBalance() - this.overdraftLimit;
		this.balance -= delta;
		this.overdraft.deposit(delta);
	}
	
	/*
	 * 	Withdraw actual account with overdraft.
	 */
	@Override
	public boolean withdraw(double amount) {
		if ((this.balance + this.overdraft.getBalance()) >= amount){
			if (this.balance > amount){
				this.balance -= amount;
				return true;
			}
			if (this.balance == 0d){
				this.overdraft.withdraw(amount);
			}
			else{
				double overdrafted = this.balance - amount;
				this.balance = 0d;
				this.overdraft.withdraw(overdrafted);
			}
			return true;
		}
		else{
			return false;
		}
	}
	
	@Override
	public String toString() {
		return "Actual balance: " + this.balance + ", overdraft: " 
				+ this.overdraft.getBalance();
	}
}